import axios from 'axios'
import router from '../router'

const isDev = process.env.NODE_ENV === 'development';

axios.defaults.baseURL = isDev ? 'http://localhost:7001' : 'http://192.0.0.1:7002'
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'

// 添加请求拦截器
axios.interceptors.request.use(function (config) {
  const TOKEN = localStorage.getItem('token')
  if (TOKEN) config.headers.common['Authorization'] = `Bearer ${TOKEN}`
  // 在发送请求之前做些什么
  return config
}, function (error) {
  // 对请求错误做些什么
  return Promise.reject(error);
});

// 添加响应拦截器
axios.interceptors.response.use(function (response) {
  // 对响应数据做点什么
  return response
}, function (error) {
  error = JSON.stringify(error)
  var res = {}
  switch(true){
    case error.indexOf('Request failed with status code 404') > -1:
      res.code = 404
      res.msg = '页面或链接不存在'
      break
    case error.indexOf('Request failed with status code 401') > -1:
      router.push('/401')
      res.code = 401
      res.msg = '无操作权限'
      break
    case error.indexOf('Request failed with status code 422') > -1:
      res.code = 422
      res.msg = '参数有误'
      break
    case error.indexOf('Request failed with status code 409') > -1:
      res.code = 409
      res.msg = '资源已存在'
      break
    case error.indexOf('Request failed with status code 413') > -1:
      res.code = 413
      res.msg = '上传数据过大，不得超过10M或20个文件'
      break
    default:
      res.msg = '未知错误'
  }
  return Promise.reject(res)
})

export default axios